package com.alogic.nginx.xscript;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Nginx的Server指令
 * 
 * @author yyduan
 * @since 1.6.12.25 [20190311 duanyy] <br>
 */
public class NginxServer extends AbstractLogiclet {
	
	/**
	 * 上下文id
	 */
	protected String pid = "$nginx-conf";

	protected String $name;
	
	protected static final Pattern p = Pattern.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}):([0-9]*)");
	
	/**
	 * 间隔
	 */
	protected String $indent = "$nginx-indent";
	
	public NginxServer(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p){
		super.configure(p);
		
		pid = PropertiesConstants.getString(p, "pid", pid,true);
		$name = PropertiesConstants.getRaw(p,"n","");
		$indent = PropertiesConstants.getString(p, "indent", $indent,true);
	}
	
	@Override
	protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
		StringBuffer content = ctx.getObject(pid);
		if (content == null){
			throw new BaseException("core.e1001","It must be in a ngx-conf context,check your script.");
		}

		String name = PropertiesConstants.transform(ctx, $name, "");
		Matcher matcher = p.matcher(name);
		if (matcher.find()){
			String host = matcher.group(1);
			String port= matcher.group(2);			
			int indent = PropertiesConstants.getInt(ctx, $indent, 0);
			String tabs = getIndent(indent);		
			content.append("\n").append(tabs).append(getCmd(host,port));			
		}

	}

	protected static String getIndent(int indent){
		return indent > 0 ? String.format(String.format("%%%ds", indent), "\t") : "";
	}
	
	protected String getCmd(String host,String port){
		return String.format("server %s:%s;", host,port);
	}
	
	public static void main(String[] args){
		Pattern p = Pattern.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}):([0-9]*)");
		
		Matcher matcher = p.matcher("10.142.90.34:8999");
		if (matcher.find()){
			System.out.println(matcher.group(1));
			System.out.println(matcher.group(2));
		}
	}
}

